<template>
  <div id="ssologin">
    <el-dialog title="绑定微信" :visible.sync="showBindFlag" center>
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="登录名" prop="userName">
          <el-input type="text" v-model="ruleForm.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm('ruleForm')">取 消</el-button>
          <el-button type="primary" @click="userPwdLogin('ruleForm')">登 录</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import login from './commonlogin.js'

// http://localhost:8286/static/juece.html#/sslogin?openid=1234
export default {
  name: 'sso-login',
  mixins: [login],
  data () {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    var userName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入登录名'))
      } else {
        callback()
      }
    }
    return {
      showBindFlag: false,
      currentOpenId: '',
      ruleForm: {
        pass: '',
        userName: ''
      },
      rules: {
        pass: [
          {validator: validatePass, trigger: 'blur'}
        ],
        userName: [
          {validator: userName, trigger: 'blur'}
        ]
      }
    }
  },
  created: function () {
    let vm = this
    let accreditCode = this.getUrlParameter(window.location.href, 'accredit_code')
    let token = this.getUrlParameter(window.location.href, 'token')
    let directUrl = this.getUrlParameter(window.location.href, 'direct_url')
    vm.currentOpenId = this.getUrlParameter(window.location.href, 'openid')
    // example:   http://localhost:8286/#/sslogin?accredit_code=0e0fa7147bebcf3e6bab77f15d55d899&token=8ae87e257e3ec005591386f235ca455a&access_token=8dc935da5a4b22c032f989c97ff04ad2&direct_url=#/physical-health
    if (token && token.length > 1) {
      console.log('单点登录，获取到token：' + token)
      // 通过token获取用户信息
      vm.getUserInfoByToken(token, function (response) {
        // 将用户信息存入缓存中
        var user = response.data.responseEntity
        vm.setUserCookie(user)
        if (directUrl && directUrl.length > 0) {
          // 跳转到指定页面
          window.location.href = directUrl
          window.location.reload()
        } else {
          // 跳转首页
          vm.loginSuccessToUrl()
        }
        // vm.getUserRightRequest(function () {
        //   if (directUrl && directUrl.length > 0) {
        //     // 跳转到指定页面
        //     window.location.href = directUrl
        //     window.location.reload()
        //   } else {
        //     // 跳转首页
        //     vm.loginSuccessToUrl()
        //   }
        // }, function (error) {
        //   console.log('getUserRightRequest error: ', error)
        // })
      }, function (error) {
        console.log('token error: ' + error)
        vm.failedToLogin()
      })
    } else if (accreditCode && accreditCode.length > 1) {
      console.log('单点登录，获取到信任码：' + accreditCode)
      // 通过信任码登录
      vm.loginByAccreditCode(accreditCode, function (response) {
        var accessToken = response.data.access_token
        if (accessToken) {
          // 通过token获取用户信息
          vm.getUserInfoByToken(accessToken, function (response) {
            // 将用户信息存入缓存中
            var user = response.data.responseEntity
            vm.setUserCookie(user)
            vm.loginSuccessToUrl()
            // vm.getUserRightRequest(function () {
            //   // 跳转首页
            //   vm.loginSuccessToUrl()
            // }, function (error) {
            //   console.log('getUserInfoByToken error: ' + error)
            // })
          }, function (error) {
            console.log('access_token error: ' + error)
            vm.failedToLogin()
          })
        } else {
          console.log('获取token失败，登录失败')
          vm.failedToLogin()
        }
      }, function (error) {
        console.log('accreditCodeLogin error: ' + error)
      })
    } else if (vm.currentOpenId && vm.currentOpenId.length > 1) {
      // 微信公众号登录 =======================================================================================================================================================
      console.log('微信公众号登录，获取到wxOpenId：' + vm.currentOpenId)
      vm.loginByOpenId(vm.currentOpenId, function (response) {
        var accessToken = response.data.access_token
        if (accessToken) {
          // 通过token获取用户信息
          vm.getUserInfoByToken(accessToken, function (response) {
            // 将用户信息存入缓存中
            var user = response.data.responseEntity
            vm.setUserCookie(user)
            vm.loginSuccessToUrl()
            // vm.getUserRightRequest(function () {
            //   // 跳转首页
            //   vm.loginSuccessToUrl()
            // }, function (error) {
            //   console.log('getUserInfoByToken error: ' + error)
            // })
          }, function (error) {
            console.log('access_token error: ' + error)
            vm.failedToLogin()
          })
        } else {
          console.log('获取token失败，登录失败')
        }
      }, function (error) {
        let code = error.errorCode
        if (code === 8009) {
          vm.$message({
            message: '微信公众号不存在',
            type: 'warning'
          })
        } else if (code === 8010) {
          vm.$message({
            message: '微信用户信息查询失败, openid 无效',
            type: 'warning'
          })
        } else if (code === 8011) {
          vm.$message({
            message: '未绑定微信公众平台帐号',
            type: 'warning'
          })
        }
        console.log('loginByOpenId error: ' + error)
        vm.showBindFlag = true
      })
    } else {
      console.log('单点登录失败,无效参数！！！！！！')
      vm.failedToLogin()
    }
  },
  methods: {
    userPwdLogin (formName) {
      let vm = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          vm.userPwdLoginRequest(vm.ruleForm.userName, vm.ruleForm.pass, function (response) {
            var accessToken = response.data.access_token
            if (accessToken) {
              // 通过token获取用户信息
              vm.getUserInfoByToken(accessToken, function (response) {
                // 将用户信息存入缓存中
                var user = response.data.responseEntity
                vm.setUserCookie(user)
                // 绑定微信账号
                vm.bindAccountByWX(vm.currentOpenId)
              }, function (error) {
                console.log('access_token error: ' + error)
                vm.failedToLogin()
              })
            } else {
              console.log('获取token失败，登录失败')
              vm.failedToLogin()
            }
          }, function (error) {
            console.log('userPwdLogin error: ' + JSON.stringify(error))
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style scoped>

</style>
